package task

import (
	"github.com/nsqio/go-nsq"
	"log"
)

type Collect struct {
	lookupdAddr string
	handlers    []*Handler
	nsqConfig   *nsq.Config
	endRunning  chan bool
}

type Handler struct {
	topic, ch string
	callback  nsq.HandlerFunc
}

func NewCollect(lookupdAddr string) *Collect {
	c := &Collect{
		lookupdAddr: lookupdAddr,
		endRunning:  make(chan bool, 1),
		handlers:    []*Handler{},
		nsqConfig:   nsq.NewConfig(),
	}

	return c
}

func (c *Collect) AddHandler(topic, ch string, callback nsq.HandlerFunc) {
	handler := &Handler{
		topic,
		ch,
		callback,
	}
	c.handlers = append(c.handlers, handler)
}

func (c *Collect) Wait() {
	<-c.endRunning
}

func (c *Collect) Run() {

	if len(c.handlers) > 0 {
		for _, handler := range c.handlers {
			log.Printf("%v", handler.topic)
			q, _ := nsq.NewConsumer(handler.topic, handler.ch, c.nsqConfig)
			q.AddHandler(nsq.HandlerFunc(handler.callback))
			err := q.ConnectToNSQLookupd(c.lookupdAddr)
			if err != nil {
				log.Printf("Could not connect")
				c.endRunning <- true
			}

		}
	}
}
